<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

function escape_html($val)
{
	if ( $val == "" )
	{
		return "";
	}

	if (is_array($val))
	{
		return array_map('escape_html', $val);
	}

	$val = str_replace( "&#032;", " ", strip_slashes($val) );

	/*
	if ( isset($this->vars['strip_space_chr']) AND $this->vars['strip_space_chr'] )
	{
		$val = str_replace( chr(0xCA), "", $val );  //Remove sneaky spaces
	}
	*/

	$val = str_replace("&"				, "&amp;"         , $val);
	$val = str_replace("<!--"			, "&#60;&#33;--"  , $val);
	$val = str_replace("-->"			, "--&#62;"       , $val);
	$val = preg_replace("/<script/i"	, "&#60;script"   , $val);
	$val = str_replace(">"				, "&gt;"          , $val);
	$val = str_replace("<"				, "&lt;"          , $val);
	//$val = str_replace('"'				, "&quot;"        , $val);
	//$val = str_replace("\n"			, "<br />"        , $val); // Convert literal newlines
	$val = str_replace("$"				, "&#036;"        , $val);
	//$val = str_replace("\r"			, ""              , $val); // Remove literal carriage returns
	$val = str_replace("!"				, "&#33;"         , $val);
	//$val = str_replace("'"				, "&#39;"         , $val); // IMPORTANT: It helps to increase sql query safety.

	// Ensure unicode chars are OK

	$val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val );

	//-----------------------------------------
	// Try and fix up HTML entities with missing ;
	//-----------------------------------------

	$val = preg_replace( "/&#(\d+?)([^\d;])/i", "&#\\1;\\2", $val );

	/*
	if ( $this->allow_unicode )
	{
		$val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val );

		//-----------------------------------------
		// Try and fix up HTML entities with missing ;
		//-----------------------------------------

		$val = preg_replace( "/&#(\d+?)([^\d;])/i", "&#\\1;\\2", $val );
	}
	*/

	return $val;
}

// file_put_contents
if (! function_exists('file_put_contents'))
{
	function file_put_contents($fileName, $data)
    {
		if (is_array($data))
		{
			$data = join('', $data);
		}

		$res = @fopen($fileName, 'w+b');

		if ($res) {
			$write = @fwrite($res, $data);

			if($write === false)
			{
				return false;
			}
			else
			{
				return $write;
			}
		}
	}
}

function mkdirs($dir, $mode = 0777, $recursive = true)
{
    if( is_null($dir) || $dir === "" )
    {
      return FALSE;
    }

    if( is_dir($dir) || $dir === "/" )
    {
      return TRUE;
    }

    if(mkdirs(dirname($dir), $mode, $recursive))
    {
      return mkdir($dir, $mode);
    }

    return false;
}

function dump($val, $return = false)
{
    $out  = "<pre style=\"background: #000; color: #ccc; font: 16px 'Consolas'; text-align: left; width: 90%; padding: 5px\">\n";
    $out .= print_r($val, true);
    $out .= "</pre>\n";

    if ($return)
    {
        return $out;
    }

    echo $out;
}

function print_a($val, $return = false)
{
	dump($val, $return);
}

function gen_link($url, $text, $target = '')
{
	$html  = "<a href=\"$url\"";
	$html .= $target ? " target=\"$target\"" : '';
	$html .= ">$text</a>";

	return $html;
}

function rmb_cap($data)
{
	$capnum=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖");
	$capdigit=array("","拾","佰","仟");
	$subdata=explode(".",$data);
	$yuan=$subdata[0];
	$j=0;
	$nonzero=0;

	for($i=0; $i<strlen($subdata[0]); $i++)
	{
		if(0==$i)
		{
			//确定个位
			if($subdata[1])
			{
				$cncap=(substr($subdata[0],-1,1)!=0) ? "元" : "元零";
			}
			else
			{
				$cncap="元";
			}
		}

		if(4==$i){ $j=0;  $nonzero=0; $cncap="万".$cncap; } //确定万位
		if(8==$i){ $j=0;  $nonzero=0; $cncap="亿".$cncap; } //确定亿位

		$numb=substr($yuan,-1,1); //截取尾数
		$cncap=($numb)?$capnum[$numb].$capdigit[$j].$cncap:(($nonzero)?"零".$cncap:$cncap);
		$nonzero=($numb)?1:$nonzero;
		$yuan=substr($yuan,0,strlen($yuan)-1); //截去尾数
		$j++;
	}

	if ($subdata[1])
	{
		$chiao=(substr($subdata[1],0,1))?$capnum[substr($subdata[1],0,1)]."角":"零";
		$cent=(substr($subdata[1],1,1))?$capnum[substr($subdata[1],1,1)]."分":"零分";
	}

	$cncap .= $chiao.$cent."整";
	$cncap=preg_replace("/(零)+/","\\1",$cncap); //合并连续“零”

	return $cncap;
}

function get_city($ip)
{
	global $db;
	$iplong = sprintf("%u", ip2long($ip));
	$city = $db->get_field("SELECT City FROM geo_ip WHERE Start <= $iplong ORDER BY End DESC LIMIT 1");
	$city = $city ? $city : "Unknown";

	return $city;
}

function verify_name($name)
{
	$name = preg_replace("/^\s*|\s*$/", "", $name);
	$name = preg_replace("/　/", " ", $name);

	if (preg_match('/^[\x{4e00}-\x{9fa5}\s]+$/u', $name))
	{
		$name = preg_replace("/\s+/", "", $name);
	}

	return $name;
}

// 计算身份证校验码，根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base)
{
	if (strlen($idcard_base) != 17)
	{
		return false;
	}

	// 加权因子
	$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);

	// 校验码对应值
	$verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
	$checksum = 0;

	for ($i = 0; $i < strlen($idcard_base); $i++)
	{
		$checksum += substr($idcard_base, $i, 1) * $factor[$i];
	}

	$mod = $checksum % 11;
	$verify_number = $verify_number_list[$mod];

	return $verify_number;
}

// 将15位身份证升级到18位
function idcard_15to18($idcard)
{
	if (strlen($idcard) != 15)
	{
		return false;
	}
	else
	{
		// 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
		if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false)
		{
			$idcard = substr($idcard, 0, 6) . '18'. substr($idcard, 6, 9);
		}
		else
		{
			$idcard = substr($idcard, 0, 6) . '19'. substr($idcard, 6, 9);
		}
	}

	$idcard = $idcard . idcard_verify_number($idcard);

	return $idcard;
}

// 18位身份证校验码有效性检查
function idcard_checksum18($idcard)
{
	if (strlen($idcard) != 18)
	{
		return false;
	}

	$idcard_base = substr($idcard, 0, 17);

	if (idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1)))
	{
		return false;
	}
	else
	{
		return true;
	}
}

function check_mail($email = '')
{
	$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";

	if (strpos($email, '@') !== false && strpos($email, '.') !== false)
	{
		if (preg_match($chars, $email))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	else
	{
		return false;
	}
}

function check_mobile($num = '')
{
	if (preg_match("/^1[3458]\d{9}$/", $num))
	{
		return TRUE;
	}

	return FALSE;
}
function check_phone($num = '')
{
	if (preg_match("/^\d{9,15}$/", $num))
	{
		return TRUE;
	}
	return FALSE;
}
function verify_sex($num='')
{
	$Sex = trim($num);
	if(is_numeric($Sex)){
		$Sex = (int)$Sex;
		if($Sex<1){
			return 0;
		}else{
			return 1;
		}
	} else {
		return 0;
	}
}
function char_conv($str) {

	$queue = Array(
		'０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
		'５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
		'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
		'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
		'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
		'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
		'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
		'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
		'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
		'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
		'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
		'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
		'ｙ' => 'y', 'ｚ' => 'z', '－' => '-', '（' => '(', '）' => ')',
		'＊' => '*', '＆' => '&', '￥' => '$', '＠' => '@', '，' => ',',
		'。' => '.', '！' => '!', '？' => '?', '；' => ';',  '×' => '*',
		'＝' => '=', '＋' => '+', '［' => '[', '］' => ']',
		'＜' => '<', '＞' => '>', '【' => '[', '】' => ']',
		'‘' => "'",	 '’' => "'",  '“' => '"',  '”' => '"',
		'　' => ' ',
	);

	$patterns = array(

	);

	$replacements = array(

	);

	foreach ($queue as $key => $value)
	{
		$patterns[] = '/' . $key . '/';
		$replacements[] = $value;
	}

	return preg_replace($patterns, $replacements, $str);

}

function get_birth($idno = '')
{
	if (strlen($idno) == 15)
	{
		$date = substr($idno, 6, 6);
	}
	else if (strlen($idno) == 18)
	{
		$date = substr($idno, 6, 8);
	}
	else
	{
		return FALSE;
	}

	if (strtotime($date))
	{
		// dump(array($idno, $date, date("Y-m-d", strtotime($date))));
		return(date("Y-m-d", strtotime($date)));
	}

	return FALSE;
}
function getIp()
{
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
    {
    	$ip = getenv("HTTP_CLIENT_IP");
    }
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
    {
    	$ip = getenv("HTTP_X_FORWARDED_FOR");
    }
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
    {
    	$ip = getenv("REMOTE_ADDR");
    }
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
    {
    	$ip = $_SERVER['REMOTE_ADDR'];
    }
    else {
    	$ip = "unknown";
    }
    return ($ip);
}

/**
* 生成随机字符串
* @param integer $length 长度
* @return string
*/
function rand_str($length = 8)
{
	$rand  = "";
	$chars = array(
		"1","2","3","4","5","6","7","8","9","0",
		"a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J",
		"k","K","l","L","m","M","n","N","o","O","p","P","q","Q","r","R","s","S","t","T",
		"u","U","v","V","w","W","x","X","y","Y","z","Z");

	$count = count($chars) - 1;

	srand((double)microtime()*1000000);

	for($i = 0; $i < $length; $i++)
	{
		$rand .= $chars[rand(0, $count)];
	}

	return($rand);
}


	/**
     * 切断给定字符串到指定长度，用mbstring函数
     *
     * @param string $str 字符串
     * @param integer $length 长度
     *
     * @return string
     */
    function str_cut($str, $length = 0)
    {
        return mb_strcut($str, 0, $length, 'utf-8');
    }

	/**
     * 切断给定字符串到指定长度，一个汉字长度计为2
     *
     * @param string $str 字符串
     * @param integer $length 长度
     *
     * @return string
     */
    function smart_cut($str, $len)
    {
        $len_utf8 = mb_strlen($str, 'utf-8');

        $cur = 0;
        $i = 0;
        $output = '';

        while ($i < $len_utf8)
        {
            $char = mb_substr($str, $i ++, 1, 'utf-8');

            if (ord($char) > 127)
            {
                $cur ++;
            }

            $cur ++;

            if ($cur > $len - 4)
            {
                $output .= ' ...';
                break;
            }

            $output .= $char;
        }

        return $output;
    }

	/**
     * 返回utf-8编码的字符串长度，一个汉字长度计为2
     *
     * @param string $str 字符串
     *
     * @return integer
     */
    function smart_len($str)
    {
        $len_utf8 = mb_strlen($str, 'utf-8');

        $len = 0;
        $i = 0;

        while ($i < $len_utf8)
        {
            $char = mb_substr($str, $i ++, 1, 'utf-8');
            if (ord($char) > 127)
            {
                $len ++;
            }

            $len ++;
        }

        return $len;
    }

	/**
     * 格式化时间
     *
     * @param integer $time 时间戳
     *
     * @return string
     */
    function format_time($time)
    {
        return date("Y-m-d H:i:s", $time);
    }

	/**
     * 格式化日期
     *
     * @param integer $time 时间戳
     *
     * @return string
     */
    function format_date($time, $fancy = false)
    {
		if ($fancy && $time > strtotime("today"))
		{
			return "今天";
		}
		elseif ($fancy && $time > strtotime("yesterday"))
		{
			return "昨天";
		}

		return date("Y-m-d", $time);
    }

    /**
     * 生成分页条
     *
     * @param integer $total 总记录数
     * @param integer $perpage 每页显示记录数
     * @param integer $page 当前页码
     * @param string $url 链接,其中的__page__将用页码替换
     *
     * @return string
     */
	function build_pagebar($total, $perpage, $page, $url)
	{
		$pages = ceil($total / $perpage);
		$page = $page <= 0 ? 1 : $page;

		$total = $total <= 0 ? 1 : $total;

        /*
		if (false === strpos($url, ".") && substr($url, -1) != '/')
		{
			$url .= '/';
		}
        */

		$html = '<div class="pages">';

        if ($pages <= 11)
        {
            $start = 1;
            $end   = $pages;
        }
        else if ($page > 6 && $page + 5 <= $pages)
        {
            $start = $page - 5;
            $end   = $page + 5;
        }
        else if ($page + 5 > $pages)
        {
            $start = $pages - 10;
            $end   = $pages;
        }
        else if ($page <= 6)
        {
            $start = 1;
            $end   = 11;
        }

		//
        if ($page == 1)
        {
            $html .= "<span>&laquo; Prev</span>";
        }
        else
        {
            $html .= "<a href=\"" . str_replace("__page__", $page - 1, $url) . "\">&laquo; Prev</a>";
        }

		if ($start > 1)
		{
			$html .= "<a href=\"" . str_replace("__page__", 1, $url) . "\">1</a>";
		}

		if ($start > 2)
		{
			$html .= "<a href=\"" . str_replace("__page__", 2, $url) . "\">2</a>";
		}

		if ($start > 3)
		{
			$html .= "<span>...</span>";
		}
		//

        for ($i = $start; $i <= $end; $i ++)
        {
            if ($page == $i)
            {
                $html .= "<a href=\"" . str_replace("__page__", $i, $url) . "\" class=\"current\">$i</a>";
            }
            else
            {
                $html .= "<a href=\"" . str_replace("__page__", $i, $url) . "\">$i</a>";
            }
        }

		if ($end < $pages - 1)
		{
			$html .= "<span>...</span>";
		}

        /*
		if ($end < $pages - 1)
		{
			$html .= "<a href=\"" . str_replace("__page__", $pages - 1, $url) . "\">" . ($pages - 1) . "</a>";
		}
        */

		if ($end < $pages)
		{
			$html .= "<a href=\"" . str_replace("__page__", $pages, $url) . "\">$pages</a>";
		}

        if ($page >= $pages)
        {
            $html .= "<span>Next &raquo;</span>";
        }
        else
        {
            $html .= "<a href=\"" . str_replace("__page__", $page + 1, $url) . "\">Next &raquo;</a>";
        }
		//

		$html .= "</div>";

		return $html;
	}

//discuz 加解密函数
// 参数解释
// $string： 明文 或 密文
// $operation：DECODE表示解密,其它表示加密
// $key： 密匙
// $expiry：密文有效期

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
    // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
    // 当此值为 0 时，则不产生随机密钥
    $ckey_length = 4;

    // 密匙
    $key = md5($key ? $key : "EDICC-zt");

    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，解密时会通过这个密匙验证数据完整性
    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上并不会增加密文的强度
    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或，再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if($operation == 'DECODE') {
        // substr($result, 0, 10) == 0 验证数据有效性
        // substr($result, 0, 10) - time() > 0 验证数据有效性
        // substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
        // 验证数据有效性，请看未加密明文的格式
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}
//删除二位数组中重复的数据
function array_unique_fb($array2D)
{
     foreach ($array2D as $v){
         $v = join(",",$v);              //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
         $temp[] = $v;
     }

    $temp = array_unique($temp);      //去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v){
        $temp[$k] = explode(",",$v);       //再将拆开的数组重新组装
    }
    return $temp;
}
function check_date($string)
{
	if(preg_match("/^(19|20)[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/",$string))
    {
    	$secMonth = 28;
    	$y = substr($string,0,4);//年
    	$m = substr($string,5,2)-1;//月
    	$d = substr($string,8,2)+0;//日

    	if(($y%4==0&&$y%100!=0)||$y%400==0){
    		$secMonth = 29;
    	}
    	$days = array(31,$secMonth,31,30,31,30,31,31,30,31,30,31);//每个月有多少天

    	for ($i = 0; $i < 12; $i++) {
    		if($m>11||$m<0){//月份不再指定范围
    			return false;
    		}else{
    			if($days[$m]<$d){//如果天数大于每个月的最大天数
    				return false;
    			}
    		}
    	}
    	return true;
    }else {
         return false;
    }
}
function check_time($string){
	if(preg_match("/((0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))$/",$string))
    {
        return true;
    }else {
         return false;
    }
}
function check_datetime($string)
{
	$d = substr($string, 0,10);
	$t = trim(substr($string, 11));
	if(check_time($t))//check_date($d)&&check_time($t)
    {
        return true;
    }else {
         return false;
    }
}

function fmDate($date){
	$year = substr($date,0,4);
    $month = substr($date,5,2);
    $day = substr($date,8,2);
    return mktime(0,0,0,$month,$day,0+$year);
}

function fmDatetime($datetime) {
    $year = substr($datetime,0,4);
    $month = substr($datetime,5,2);
    $day = substr($datetime,8,2);
    $hour = substr($datetime,11,2);
    $min = substr($datetime,14,2);
    $sec = substr($datetime,17,2);
    return mktime($hour,$min,$sec,$month,$day,0+$year);
}
/**
 *
 * 根据生日获取投保对象的类型，获取年龄
 * @param String $birth 生日 2001-12-05
 * @param $efftime $birth 生日 2011-12-05
 */
function cacuAge($birth,$efftime,$fix=false)
{
	$date = $efftime ? substr($efftime,0,10) : date("Y-m-d");

	$tmp = $bdstr = $datestr = "";

	$tmp = explode('-', $birth);
	$bdstr = intval($tmp[1])*100 + intval($tmp[2]);

	$tmp = explode('-', $date);

	$datestr = intval($tmp[1])*100 + intval($tmp[2]);

	$age = date("Y", strtotime($date)) - date("Y", strtotime($birth));

	if($fix===true){
		$rs=diffDateTime($birth,$efftime);
		$l=CountLeapYear($birth,$efftime);
		$rs['day']=$rs['day']-$l;
		$m=$rs['day']/365;
		$s=$m-$age;
		$age=$age+number_format($s,2,'.','');
	}else{
		$age = $datestr > $bdstr ? $age+1 : $age;//年份不同，只有在 $efftime 大于出生日期的时候在+1岁
	}
	return $age;
}
/**
 *
 * 根据年份区间包含的润年年费数量
 * @param String $DateStart  2001-12-05
 * @param $efftime $DateEnd  2011-12-05
 */
function CountLeapYear($DateStart,$DateEnd){
	$TmpS = explode('-', $DateStart);
	$TmpE = explode('-', $DateEnd);
	$s=$TmpS['0'];
	$e=$TmpE['0'];
	if($TmpS['1']>'02'){
		$s++;
	}
	if($TmpE['1']<'03'){
		$e--;
	}
	$r=0;
	for($y=$s;$y<=$e;$y++)
	{
		if(($y%4==0&&$y%100!=0)||$y%400==0){
	    	$r++;
	    }
	}
	return $r;
}

/**
 *
 * 根据生日获取投保对象的类型，确定是否为同一天
 * @param String $birth 生日 2001-12-05
 * @param $efftime $birth 生日 2011-12-05
 */
function checkSameDay($birth,$efftime){
	$date = $efftime ? substr($efftime,0,10) : date("Y-m-d");

	$tmp = $bdstr = $datestr = "";

	$tmp = explode('-', $birth);
	$bdstr = intval($tmp[1])*100 + intval($tmp[2]);

	$tmp = explode('-', $date);
	$datestr = intval($tmp[1])*100 + intval($tmp[2]);

	$sameDay = $datestr == $bdstr ? true : false;

	return $sameDay;
}

/**
 *
 * 根据俩个时间获取俩个时间的 包含的  年，月数，天数，小时，分钟，秒
 * @param String $start
 * @param String $end
 * @return ArrayObject
 * _diffDateTime('2009-10-12 23:41:22','2011-12-14 22:24:00')
 */
function diffDateTime($DateStart,$DateEnd){
	$rs = array();

	$sYear = intval(substr($DateStart,0,4));
	$eYear = intval(substr($DateEnd,0,4));

	$sMonth = intval(substr($DateStart,5,2));
	$eMonth = intval(substr($DateEnd,5,2));

	$sDay = intval(substr($DateStart,8,2));
	$eDay = intval(substr($DateEnd,8,2));

	$startTime = fmDatetime($DateStart);
	$endTime = fmDatetime($DateEnd);
	$dis = $endTime-$startTime;//得到俩个时间的秒数
	$d = ceil($dis/(24*60*60));//得到天数
	$rs['day'] = $d;//天数
	$rs['hour'] = ceil($dis/(60*60));//小时
	$rs['minute'] = ceil($dis/60);//分钟
	$rs['second'] = $dis;//秒数
	$rs['week'] = ceil($d/7);//周

	$tem = ($eYear-$sYear)*12;//月份
	$tem1 = $eYear-$sYear;//年
	if($eMonth-$sMonth<0){//月份相减为负
		$tem +=($eMonth-$sMonth);
		if($eDay>=$sDay){
			$tem++;
		}
	}else if($eMonth==$sMonth){//月份相同
		if($eDay>=$sDay){
			$tem ++;
			$tem1++;
		}
	}else if($eMonth-$sMonth>0){//月份相减正负
		$tem1++;
		if($eDay>=$sDay){//且日期相减为正数
			$tem +=($eMonth-$sMonth)+1;
		}else{
			$tem +=($eMonth-$sMonth);
		}
	}
	$rs['month'] = $tem;
	$rs['year'] = $tem1;

	return $rs;
}

/**
 *
 * 显示信息
 * @param String $message
 * @param String $url
 * @return ArrayObject
 * showmessage('要显示的内容','要跳转的url地址')
 */
 function showmessage($message,$url = 'goback')
 {
 	//$ci = & get_instance();
 	$show = '';
 	if($url=='goback')
 	{
 		$show .= '<center><table border=1 width=200><tr><td>提示信息</td></tr><tr><td>';
 		$show .= $message;
 		$show .= '</td></tr><tr><td><a href="javascript:history.go(-1);">返回上一页</a></td></tr></table></center>';
 	}
 	else
 	{
 		$show .= '<center><table border=1 width=200><tr><td>提示信息</td></tr><tr><td>';
 		$show .= $message;
 		$show .= '</td></tr><tr><td><a href="'.$url.'">如果没自动跳转，请点击这里</a></td></tr></table></center>';
 		$show .= '<script language=javascript> setTimeout("window.location=\'' . $url . '\'",1500); </script>';
 	}
 	echo $show;
 	//$ci->load->view('admin/showmessage_tpl',$show);
 }
